package com.bit.lotterySystem.controller;

import com.bit.lotterySystem.common.errorcode.ControllerErrorCodeConstants;
import com.bit.lotterySystem.common.exception.ControllerException;
import com.bit.lotterySystem.common.pojo.CommonResult;
import com.bit.lotterySystem.common.utils.JacksonUtil;
import com.bit.lotterySystem.controller.param.UserRegisterParam;
import com.bit.lotterySystem.controller.result.UserRegisterResult;
import com.bit.lotterySystem.service.UserService;
import com.bit.lotterySystem.service.VerificationCodeService;
import com.bit.lotterySystem.service.dto.UserRegisterDto;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController

public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private VerificationCodeService verificationCodeService;

    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(@Validated @RequestBody UserRegisterParam param) {
        logger.info("userRegister UserRegisterParam: {}", JacksonUtil.writeValueAsString(param));
        UserRegisterDto userRegisterDto =  userService.register(param);
//        UserRegisterResult result = new UserRegisterResult();
//        BeanUtils.copyProperties(userRegisterDto, result);
//        return CommonResult.success(result);
        return CommonResult.success(converToRegisterResult(userRegisterDto));
    }
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerificationCode(String phoneNumber) {
        logger.info("sendVerificationCode({})", phoneNumber);
        verificationCodeService.sendVerificationCode(phoneNumber);
        return CommonResult.success(true);
    }

    private UserRegisterResult converToRegisterResult(UserRegisterDto userRegisterDto) {
        if(userRegisterDto == null) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }
        UserRegisterResult userRegisterResult = new UserRegisterResult();
        userRegisterResult.setUserId(userRegisterDto.getUserId());
        return userRegisterResult;
    }
}
